import { ref, watch } from 'vue'
import { useAppStore } from '@/stores/app'
import { getThemeSettings, updateThemeSettings } from '@/api/user_settings'

/**
 * 主题Hook
 * @returns {Object} 主题相关方法和状态
 */
export function useTheme() {
  const appStore = useAppStore()
  const themeLoading = ref(false)
  const currentTheme = ref(appStore.theme)

  // 监听主题变化
  watch(currentTheme, (newTheme) => {
    appStore.setTheme(newTheme)
  })

  /**
   * 切换主题
   * @param {string} theme 主题名称
   */
  const toggleTheme = async (theme) => {
    try {
      themeLoading.value = true
      await updateThemeSettings({ theme })
      currentTheme.value = theme
    } catch (error) {
      console.error('切换主题失败:', error)
    } finally {
      themeLoading.value = false
    }
  }

  /**
   * 初始化主题
   */
  const initTheme = async () => {
    try {
      themeLoading.value = true
      const { data } = await getThemeSettings()
      if (data?.theme) {
        currentTheme.value = data.theme
      }
    } catch (error) {
      console.error('初始化主题失败:', error)
    } finally {
      themeLoading.value = false
    }
  }

  /**
   * 重置主题
   */
  const resetTheme = async () => {
    try {
      themeLoading.value = true
      await updateThemeSettings({ theme: 'light' })
      currentTheme.value = 'light'
    } catch (error) {
      console.error('重置主题失败:', error)
    } finally {
      themeLoading.value = false
    }
  }

  return {
    themeLoading,
    currentTheme,
    toggleTheme,
    initTheme,
    resetTheme
  }
} 